﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using Newtonsoft.Json;
using DevExpress.Web.Mvc;
using System.IO;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class SubOfficeDeptController : AdminBaseController
    {
        BLL.HRDept deptBll = new BLL.HRDept();
        BLL.SubOfficeDeptDocCls SubOfficeDeptDocClsbll = new BLL.SubOfficeDeptDocCls();
        BLL.SubOfficeDeptDocClsEntry SubOfficeDeptDocClsEntrybll = new BLL.SubOfficeDeptDocClsEntry();
        public string entityNo = GlobalConstant.ENTITYNO;
        BLL.SubOfficeDeptTemplate depttempbll = new BLL.SubOfficeDeptTemplate();
        BLL.SubOfficeTempCls tempclsbll = new BLL.SubOfficeTempCls();
        BLL.SubOfficeTemplate tempbll = new BLL.SubOfficeTemplate();
       //默认模板id
         string defaulttempid = "01";

        //默认顶部图片
         string defaulttoppic = "/Content/template/top01.jpg";       
        //
        // GET: /Admin/SubOfficeDept/
        [AuthorityActionFilter("m_SubOfficeDept", Order = 1)]
        [LogPageActionFilter("科室导航管理", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 部门树
        /// </summary>
        /// <returns>返回部门树视图</returns>
        public ActionResult DeptTree(string focusNodeName = "")
        {
            BLL.HRDept deptBll = new BLL.HRDept();
            TreeModelList treeModelList = new TreeModelList();

            List<Model.HRDept> deptAllList = new List<Model.HRDept>();
            deptAllList = deptBll.GetListByEntityNo(GlobalConstant.ENTITYNO).Where(h=>h.FIsAgency=="N").ToList();
            if (deptAllList.Count > 0)
            {
                List<Model.HRDept> deptlist = (from c in deptAllList where c.FParentDeptNo == null orderby c.FSeq select c).ToList();

                foreach (Model.HRDept dept in deptlist)
                {
                    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                    {
                        Id = dept.FDeptNo,
                        Name = dept.FDeptName,
                        ImageUrl = Url.Content("~/Content/ControlImages/dept_Groups.png")
                    };

                    List<Model.HRDept> deptModelList = (from c in deptAllList where c.FParentDeptNo == dept.FDeptNo orderby c.FSeq select c).ToList();
                    if (deptModelList.Count > 0)
                    {
                        GetChildDept(deptModelList, treeParentItemModel, deptAllList);
                    }

                    treeModelList.Add(treeParentItemModel);
                }

            }
            ViewData["focusNodeName"] = focusNodeName;
            return View(treeModelList);
        }

        /// <summary>
        /// 递归获取部门树
        /// </summary>
        /// <param name="deptChildList">部门列表</param>
        /// <param name="treeParentItemModel">父级树节点</param>
        /// <param name="deptAllList">部门集合</param>
        private void GetChildDept(List<Model.HRDept> deptChildList, TreeItemModel treeParentItemModel, List<Model.HRDept> deptAllList)
        {
            foreach (Model.HRDept dept in deptChildList)
            {

                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = dept.FDeptNo,
                    Name = dept.FDeptName,
                    ImageUrl = Url.Content("~/Content/ControlImages/dept_Groups.png")
                };

                List<Model.HRDept> deptModelList = (from c in deptAllList where c.FParentDeptNo == dept.FDeptNo orderby c.FSeq select c).ToList();

                if (deptModelList.Count > 0)
                {
                    GetChildDept(deptModelList, treeChildItemModel, deptAllList);
                }

            }

        }
        /// <summary>
        /// 科室导航编辑视图
        /// </summary>
        /// <param name="deptNo">部门编号</param>
        /// <returns></returns>
        public ActionResult DeptContent(string deptNo)
        {
            //栏目名称集合
            Dictionary<int, string> docstrlist = new Dictionary<int, string>();
            //取出对应的主栏目和同时显示栏目
            List<Model.SubOfficeDeptDocCls> SubOfficeDeptDocClslist = SubOfficeDeptDocClsbll.GetModelList("t_docCls.FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "' ORDER BY dbo.t_docCls.FSeq");
            List<Model.SubOfficeDeptDocClsEntry> SubOfficeDeptDocClsEntrylist = SubOfficeDeptDocClsEntrybll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'");
            Dictionary<int, Models.CommonValueModel> diccls = new Dictionary<int, Models.CommonValueModel>();
            // ViewData["ids"] = JsonConvert.SerializeObject(docstrlist);
            Dictionary<int, List<Models.CommonValueModel>> dicentry = new Dictionary<int, List<Models.CommonValueModel>>();
            //循环增加每个主栏目对应的同时显示栏目,为空时新建
            int a = 0;
            foreach (Model.SubOfficeDeptDocCls s in SubOfficeDeptDocClslist)
            {
                a++;
                if (SubOfficeDeptDocClsEntrylist.Where(h => h.FDocClsCd == s.FDocClsCd).Count() > 0)
                {
                    Models.CommonValueModel first = new Models.CommonValueModel() { Text = s.FDocClsCd, Value = s.FDocClsCd };
                    List<Models.CommonValueModel> nexts = new List<Models.CommonValueModel>();
                    foreach (Model.SubOfficeDeptDocClsEntry e in SubOfficeDeptDocClsEntrylist.Where(h => h.FDocClsCd == s.FDocClsCd).ToList())
                    {

                        nexts.Add(new Models.CommonValueModel() { Text = e.FShowDocClsCd, Value = e.FShowDocClsCd });
                    }

                    diccls.Add(a, first);

                    dicentry.Add(a, nexts);
                }
                else
                {
                    Models.CommonValueModel first = new Models.CommonValueModel() { Text = s.FDocClsCd, Value = s.FDocClsCd };
                    List<Models.CommonValueModel> nexts = new List<Models.CommonValueModel>();

                    diccls.Add(a, first);

                    dicentry.Add(a, nexts);
                }
            }
            ViewData["jsonentrys"] = JsonConvert.SerializeObject(dicentry);
            ViewData["jsondiccls"] = JsonConvert.SerializeObject(diccls);
            ViewData["entrys"] = dicentry;
            ViewData["diccls"] = diccls;
            ViewData["DeptNo"] = deptNo;
            List<Model.SubOfficeTempCls> tempclslist = tempclsbll.GetModelList("").ToList();
            List<Model.SubOfficeTemplate> templist = tempbll.GetModelList("").ToList();
            Model.SubOfficeDeptTemplate depttemp = depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'").Count > 0 ? depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'").FirstOrDefault() : null;
            ViewData["fmode"] = depttemp == null ? "P" : (depttemp.FTemplTopPicMode == "F" ? "F" : "P");
            ViewData["templist"] = templist;
            //默认图片
            ViewData["defpic"] = defaulttoppic;
            ViewData["tempclslist"] = tempclslist;
            //选择部门id
            ViewData["seldepttempid"] = depttemp == null ? defaulttempid : depttemp.FTempID;
            //默认顶部图片
          ViewData["topic"] = depttemp == null ? defaulttoppic : (string.IsNullOrEmpty(depttemp.FTemplTopPicPath)?defaulttoppic:(depttemp.FTemplTopPicMode=="P"?depttemp.FTemplTopPicPath:""));
          ViewData["tosavepic"] = depttemp == null ? defaulttoppic : (string.IsNullOrEmpty(depttemp.FTemplTopPicPath) ? defaulttoppic : depttemp.FTemplTopPicPath);
            
            return View("DeptContent", SubOfficeDeptDocClslist);
        }

        /// <summary>
        /// 显示缩略图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult IndexImage(string pt)
        {
            if (!string.IsNullOrEmpty(pt))
            {


                string strNewImgPath = Url.Content(pt);

                if (GenerateUtil.ExistsFile(strNewImgPath))//图片存在
                {
                    int width = 300;
                    int height = 300;
                    byte[] imgs = OperateImg.breviaryImg(width, height, strNewImgPath, 0);

                    Response.AppendHeader("Content-Length", imgs.Length.ToString());

                    //Response.Clear();
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(imgs);
                    Response.End();
                }
                else
                {
                    return View();
                }
            }
            else
            {
                return View();
            }
            return View();

        }

        /// <summary>
        /// 保存视图
        /// </summary>
        /// <returns></returns>
        /// 

        [ValidateInput(false)]
        public ActionResult Save()
        {
            //默认路径
            string strDefaultAttachPath = Url.Content("~/Publish/" + entityNo + "/" + "DocClsLOGO/");
            string url = Server.MapPath(strDefaultAttachPath);
            if (!Directory.Exists(url))
            {
                Directory.CreateDirectory(url);
            }
            //图片还是flash模式
            string fmode = ComboBoxExtension.GetValue<string>("modeSelect");
            string filenm = "";
            bool hasfile = false;
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].ContentLength > 0)
                {
                    hasfile = true;
                }
            }
            if (hasfile)
            {
                System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    //上传附件
                    if (Request.Files[i].ContentLength > 0)
                    {
                        HttpPostedFileBase upload = Request.Files[i];
                        string type = upload.ContentType;//获取文件类型
                        string extension = Path.GetExtension(upload.FileName).ToLower();
                        string factFileName = Path.GetFileNameWithoutExtension(upload.FileName) + extension;//获取文件名称

                        string fullpath = url + factFileName;
                        if (System.IO.File.Exists(fullpath) == true)
                        {
                            System.IO.File.Delete(fullpath);
                        }
                        upload.SaveAs(fullpath);
                        filenm = strDefaultAttachPath + factFileName;
                    }
                }
            }
            else
            {
                filenm = "";
            }
            //获取到主栏目与同时显示栏目保存隐藏域
            string deptno = Fetch.Post("hdeptno");
            string DicClsJson = Fetch.Post("hDicClsJson");
            string dDicEntryJson = Fetch.Post("hdDicEntryJson");

            //当前部门模板
            Model.SubOfficeDeptTemplate depttemp = depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").Count > 0 ? depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").FirstOrDefault() : null;
            //循环遍历radiobutton
            List<Model.SubOfficeTemplate> templist = tempbll.GetModelList("").ToList();

            bool hastemp = false;
            foreach (Model.SubOfficeTemplate tmp in templist)
            {
                
                string s = RadioButtonExtension.GetValue<string>("moban" + tmp.FTempID);
                if (bool.Parse(s))
                {
                    hastemp = true;
                    if (depttemp == null)
                    {

                        Model.SubOfficeDeptTemplate dtmp = new Model.SubOfficeDeptTemplate();
                        dtmp.FDeptNo = deptno;
                        dtmp.FEntityNo = entityNo;
                        dtmp.FTempID = tmp.FTempID;
                        dtmp.FTemplTopPicMode = string.IsNullOrEmpty(filenm) ? "P" : (string.IsNullOrEmpty(fmode) ? "P" : fmode);
                        //原来的
                        //dtmp.FTemplTopPicPath = filenm;
                        string hfilename = Fetch.Post("tosavepic");
                        dtmp.FTemplTopPicPath = string.IsNullOrEmpty(filenm) ? hfilename : filenm;
                        depttempbll.Add(dtmp);
                    }
                    else
                    {
                        Model.SubOfficeDeptTemplate dtmp = new Model.SubOfficeDeptTemplate();
                        dtmp.FDeptNo = deptno;
                        dtmp.FEntityNo = entityNo;
                        dtmp.FTempID = tmp.FTempID;
                        //原来的
                       // dtmp.FTemplTopPicMode = string.IsNullOrEmpty(filenm) ?  depttemp.FTemplTopPicMode:(string.IsNullOrEmpty(fmode) ? "P" : fmode) ;
                        dtmp.FTemplTopPicMode = string.IsNullOrEmpty(fmode) ? "P" : fmode;
                        //如果没上传文件,默认去隐藏域
                        string hfilename = Fetch.Post("tosavepic");
                        //原来的
                      //  dtmp.FTemplTopPicPath =string.IsNullOrEmpty(filenm)?depttemp.FTemplTopPicPath :filenm;
                        dtmp.FTemplTopPicPath = string.IsNullOrEmpty(filenm) ? hfilename : filenm;
                        depttempbll.Update(dtmp);
                    }
                }
            }
            if (!hastemp)
            {
                if (depttemp == null)
                {

                    Model.SubOfficeDeptTemplate dtmp = new Model.SubOfficeDeptTemplate();
                    dtmp.FDeptNo = deptno;
                    dtmp.FEntityNo = entityNo;
                    dtmp.FTempID = defaulttempid;
                    dtmp.FTemplTopPicMode = string.IsNullOrEmpty(filenm) ? "P" : (string.IsNullOrEmpty(fmode) ? "P" : fmode);
                    //dtmp.FTemplTopPicPath = filenm;
                    string hfilename = Fetch.Post("tosavepic");
                    dtmp.FTemplTopPicPath = string.IsNullOrEmpty(filenm) ? hfilename : filenm;
                    depttempbll.Add(dtmp);
                }
                else
                {
                    Model.SubOfficeDeptTemplate dtmp = new Model.SubOfficeDeptTemplate();
                    dtmp.FDeptNo = deptno;
                    dtmp.FEntityNo = entityNo;
                    dtmp.FTempID = defaulttempid;
                    //原来的
                   // dtmp.FTemplTopPicMode = string.IsNullOrEmpty(filenm) ? depttemp.FTemplTopPicMode : (string.IsNullOrEmpty(fmode) ? "P" : fmode);
                    dtmp.FTemplTopPicMode = string.IsNullOrEmpty(fmode) ? "P" : fmode;
                 //   dtmp.FTemplTopPicPath = string.IsNullOrEmpty(filenm) ? depttemp.FTemplTopPicPath : filenm;
                    string hfilename = Fetch.Post("tosavepic");
                    dtmp.FTemplTopPicPath = string.IsNullOrEmpty(filenm) ? hfilename : filenm;
                    depttempbll.Update(dtmp);
                }
            }
            //反序列化栏目
            Dictionary<int, Models.CommonValueModel> diccls = new Dictionary<int, Models.CommonValueModel>();

            Dictionary<int, List<Models.CommonValueModel>> dicentry = new Dictionary<int, List<Models.CommonValueModel>>();
            List<Model.SubOfficeDeptDocCls> mdicclslist = new List<Model.SubOfficeDeptDocCls>();
            List<Model.SubOfficeDeptDocClsEntry> mdicentrylist = new List<Model.SubOfficeDeptDocClsEntry>();
            diccls = JsonConvert.DeserializeObject<Dictionary<int, Models.CommonValueModel>>(DicClsJson);
            dicentry = JsonConvert.DeserializeObject<Dictionary<int, List<Models.CommonValueModel>>>(dDicEntryJson);
            //去除空项,cnt总计
            int cnt = diccls.Count;
            for (int i = 1; i <cnt + 1; i++)
            {
                if (string.IsNullOrEmpty(diccls[i].Value.ToString()))
                {
                    diccls.Remove(i);
                    dicentry.Remove(i);
                }

            }
            if (diccls.Count == 0)
            {
                ViewData["jsAlert"] = "必须包含栏目信息";
                return DeptContent(deptno);
            }

            if (diccls.Count != dicentry.Count)
            {
                ViewData["jsAlert"] = "错误:主栏目与同时显示栏目结果不匹配";
                return DeptContent(deptno);
            }
            //通过groupby判断是否有重复主栏目
            if (diccls.Values.GroupBy(h => h.Value).Where(y => y.Count() > 1).Count() > 0)
            {
                ViewData["jsAlert"] = "错误:不能包含重复的主栏目";
                return DeptContent(deptno);
            }
           
            //循环生成主栏目和同时显示栏目的列表
            foreach (KeyValuePair<int, Models.CommonValueModel> kv in diccls)
            {
                mdicclslist.Add(new Model.SubOfficeDeptDocCls()
                {
                    FEntityNo = entityNo,
                    FDeptNo = deptno,
                    FDocClsCd = kv.Value.Value

                });
                foreach (Models.CommonValueModel kventry in dicentry[kv.Key])
                {
                    mdicentrylist.Add(new Model.SubOfficeDeptDocClsEntry()
                    {
                        FEntityNo = entityNo,
                        FDeptNo = deptno,
                        FDocClsCd = kv.Value.Value,


                        FShowDocClsCd = kventry.Value

                    });
                }
            }
            //在数据库使用事务判断提交
            try
            {
                string sout = SubOfficeDeptDocClsbll.AddAll(mdicclslist, mdicentrylist, entityNo, deptno);
                if (sout == "ok")
                {
                    ViewData["RedirectURL"] = Url.Action("DeptContent", "SubOfficeDept", new { deptNo = deptno });

                    return View("SuccessMessagePage");

                }
                else
                {
                    ViewData["jsAlert"] = sout;
                    return DeptContent(deptno);

                }

            }
            catch (System.Exception ex)
            {
                ViewData["jsAlert"] = "错误:" + ex.Message;

                return DeptContent(deptno);

            }
        }
    }
}